package com.blog.websocket;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

// 确保路径与前端一致
@ServerEndpoint("/websocket/notification/{userId}")
@Component
public class NotificationWebSocket {

    private static final Logger log = LoggerFactory.getLogger(NotificationWebSocket.class);

    // 存储用户ID与会话的映射
    private static final Map<Long, Session> clients = new ConcurrentHashMap<>();
    private static final ObjectMapper objectMapper = new ObjectMapper();

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") Long userId) {
        log.info("新的WebSocket连接: userId={}", userId);
        clients.put(userId, session);
    }

    @OnClose
    public void onClose(@PathParam("userId") Long userId) {
        log.info("WebSocket连接关闭: userId={}", userId);
        clients.remove(userId);
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        // 处理来自客户端的消息
        log.info("收到客户端消息: {}", message);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("WebSocket错误", error);
    }

    /**
     * 发送通知给指定用户
     * @param userId 用户ID
     * @param notification 通知内容
     */
    public static void sendNotification(Long userId, JSONObject notification) {
        Session session = clients.get(userId);
        if (session != null && session.isOpen()) {
            try {
                String message = notification.toString();
//                String message = objectMapper.writeValueAsString(notification);
                session.getAsyncRemote().sendText(message);
                log.info("通知发送成功: userId={}, message={}", userId, message);
            } catch (Exception e) {
                log.error("通知序列化失败", e);
            }
        } else {
            log.info("用户不在线，无法发送通知: userId={}", userId);
        }
    }

    /**
     * 获取在线用户数
     */
    public static int getOnlineCount() {
        return clients.size();
    }
}
